package com.cxb.servicemap.remote;

import com.cxb.internalcommon.constant.AmapConfigConstants;
import com.cxb.internalcommon.dto.ResponseResult;
import com.cxb.internalcommon.responese.TerminalResponse;
import com.cxb.internalcommon.responese.TrackResponse;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

@Service
public class TrackClient {

    @Value("${amap.key}")
    private String amapKey;
    @Value("${amap.sid}")
    private String amapSid;
    @Autowired
    private RestTemplate restTemplate;

    public ResponseResult<TrackResponse> addTrack(String tid){
        StringBuilder urlBuild = new StringBuilder();
        urlBuild.append(AmapConfigConstants.TRACK_ADD);
        urlBuild.append("?");
        urlBuild.append("key="+amapKey);
        urlBuild.append("&");
        urlBuild.append("sid="+amapSid);
        urlBuild.append("&");
        urlBuild.append("tid="+tid);

        ResponseEntity<String> stringResponseEntity = restTemplate.postForEntity(urlBuild.toString(), null, String.class);
        /**
         *         {
         *             "errcode": 10000,
         *             "errmsg": "OK",
         *                 "data": {
         *                     "name": "车辆2",
         *                     "tid": 974313004,
         *                     "sid": 1036849
         *                  }
         *         }
         */
        String body = stringResponseEntity.getBody();
        JSONObject jsonObject = JSONObject.fromObject(body);
        JSONObject data = jsonObject.getJSONObject("data");
        //轨迹id和name
        String trid = data.getString("trid");
        String trname = "";
        if(data.has("trname")){
            trname = data.getString("trname");
        }

        TrackResponse trackResponse = new TrackResponse();
        trackResponse.setTrid(trid);
        trackResponse.setTrname(trname);
        return ResponseResult.success(trackResponse);
    }
}
